package com.kayo.specimen.intercepter;

import com.kayo.specimen.model.User;
import com.kayo.specimen.model.view.UserView;
import com.kayo.specimen.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CurrentUserInterceptor implements HandlerInterceptor {
    @Autowired
    public UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String code = SecurityUtils.getSubject().getPrincipal().toString();
            List<UserView> users = userService.getUsers(code, null, null, null);
            if (!users.isEmpty())
                request.setAttribute("currentUser", users.get(0));
        } catch (Exception ignored) {

        }
        return true;
    }
}
